package com.iMusic.presentationLayer;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.iMusic.businessLogicLayer.Account;
import com.iMusic.businessLogicLayer.Cart;
import com.iMusic.businessLogicLayer.Product;

public class RecalculateCart extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String redirection = "cartFS.jsp";
		HttpSession session = request.getSession();
		Account account = (Account) session.getAttribute("Account");
		Cart cart = (Cart) session.getAttribute("Cart");

		for (Product prod : cart.getProducts()) {
			String qttStr = request.getParameter(prod.getProductId().toString());
			if (qttStr != null) {
				int newQtt = Integer.parseInt(qttStr);
				if ((newQtt <= prod.getUnitsInStock() && newQtt != cart.getQuantity(prod)) || prod.getUnitsInStock() < 0) {
					cart.setNewQuantity(prod, newQtt);
				}
			}
		}
		
		session.removeAttribute("Cart");
		session.setAttribute("Cart", cart);
		
		response.sendRedirect(redirection);
	}
}
